package com.itheima.reggie.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


// 购物车
@Service
@Transactional
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;

    //添加购物车参数
    @Override
    public Cart add(Cart cartParam) {
        // 1.先查询购物车是否有数据
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        //select * from shopping_cart where user_id= ?  and (dish_id=?  | setmeal_id =?)
        qw.eq(Cart::getUserId, UserHolder.get().getId());//查找数据库中id是否存在
        qw.eq(cartParam.getDishId() != null, Cart::getDishId, cartParam.getDishId());//查找购物车中菜品id是否存在
        qw.eq(cartParam.getSetmealId() != null, Cart::getSetmealId, cartParam.getSetmealId());//查找购物车中套餐id是否存在
        //查询到购物车的数据
        Cart cart = cartMapper.selectOne(qw);

        if (cart == null) {
            cartParam.setUserId(UserHolder.get().getId());
            // 补全数量
            cartParam.setNumber(1);
            // 手动填充时间
            cartParam.setCreateTime(new Date());
            cart = cartParam;
            cartMapper.insert(cart);

        } else {
            cart.setNumber(cart.getNumber() + 1);
            cartMapper.updateById(cart);
        }
        return cart;
    }

    // 查看购物车列表
    @Override
    public List<Cart> list() {

        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        qw.eq(Cart::getUserId, UserHolder.get().getId());
        return cartMapper.selectList(qw);
    }

    //清空购物车
    @Override
    public void delete() {
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        qw.eq(Cart::getUserId, UserHolder.get().getId());
        cartMapper.delete(qw);
    }

    //减少购物车参数
    @Override
    public Cart sub(Cart cartParam) {
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        //select * from shopping_cart where user_id= ?  and (dish_id=?  | setmeal_id =?)
        qw.eq(Cart::getUserId, UserHolder.get().getId());//查找数据库中id是否存在
        qw.eq(cartParam.getDishId() != null, Cart::getDishId, cartParam.getDishId());//查找购物车中菜品id是否存在
        qw.eq(cartParam.getSetmealId() != null, Cart::getSetmealId, cartParam.getSetmealId());//查找购物车中套餐id是否存在
        Cart cart = cartMapper.selectOne(qw);

        //如果购物车有参数
        if (cart.getNumber() > 0) {
            cart.setNumber(cart.getNumber() - 1);
            cartMapper.updateById(cart);
        }
        if (cart.getNumber() == 0) {
            cartMapper.deleteById(cart.getId());
        }
        return cart;
    }
}
